//
//  CAIShareKit.h
//  CollagePicture
//
//  Created by simon on 2021/12/2.
//

#import "ShareManager.h"
#import <objc/runtime.h>
#import <objc/message.h>



static NSString *const kAppKeyUMTest = @"555daf0767e58e8c7100260f";

// 微信url scheme:appId
static NSString *kAppKeyWeChatTest = @"wx0d4c10b45e46d89c";
static NSString *kAppSecretWeChatTest = @"83d977878367c60d240e17e526111ebb";
// 和配置的需要一样
static NSString *kUniversalLinkWeChatTest = @"https://daily-g.520chs.com/public/";

static NSString *kAppKeyDingDingTest = @"dingmpwf79gn1ldk9xy2";
static NSString *kAppSecretDingDingTest = @"eG3FxswpjkSdLZI-ryVxJcYFXamUy1-rVm9i_KzQOjLiGnhV5XqL0VojOFKuZahe";


//新浪微博 url scheme:wb+appkey
static NSString *kAppKeySina = @"3381787410";
static NSString *kAppSecretSina = @"b496454d3f86f3b7d33b3fb25bcd6fdd";



@interface ShareManager()

@end

@implementation ShareManager

+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id obj = nil;
    dispatch_once(&once, ^{
        obj = [[self alloc]init];
    });
    return obj;
}

#pragma mark
#pragma mark-umeng社会化分享

- (void)initWithAppKey:(NSString *)appKey
{
    // 初始化基础组件库
//    [UMConfigure initWithAppkey:appKey channel:nil];
    Class cls = objc_getClass("UMConfigure");//NSClassFromString(@"UMConfigure");
    void (*umConfigure_msgSend)(id,SEL,NSString *,NSString *) = (void (*)(id, SEL,NSString *,NSString *))objc_msgSend;
    umConfigure_msgSend(cls,sel_registerName("initWithAppkey:channel:"),appKey,nil);

    // U-Share 默认基础设置
    [self initSettings];
}


///
- (void)initSettings{
    
    ((void(*)(id,SEL,BOOL))objc_msgSend)([ShareManager umSocialGlobal],sel_registerName("setIsUsingHttpsWhenShareContent:"),NO);

    ///默认通用链接设置
    [self setUniversalLinkDic:nil];


//   //关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
//    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
//    //打开图片水印，不管用
//    [UMSocialGlobal shareInstance].isUsingWaterMark = YES;
//    [UMSocialGlobal shareInstance].warterMarkConfig = [UMSocialWarterMarkConfig defaultWarterMarkConfig];
}

///Universal Links设置
- (void)setUniversalLinkDic:(NSDictionary *)dic{
    
    NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    if (![dic objectForKey:  @(CAISocialPlatformType_WechatSession)]) {
        [mDic setObject:kUniversalLinkWeChatTest forKey:@(CAISocialPlatformType_WechatSession)];
    }
    ((void(*)(id, SEL, id))objc_msgSend)([ShareManager umSocialGlobal],sel_registerName("setUniversalLinkDic:"),[mDic copy]);
    
//    //Universal Links设置
//    [UMSocialGlobal shareInstance].universalLinkDic = @{
//  @(UMSocialPlatformType_WechatSession):kUniversalLinkWeChatTest
//    };
}

-(void)configUShareDefaultPlatforms{
    ///设置平台的appKey
    [self setPlaform:CAISocialPlatformType_WechatSession appKey:kAppKeyWeChatTest appSecret:kAppSecretWeChatTest];
    [self setPlaform:CAISocialPlatformType_DingDing appKey:kAppKeyDingDingTest appSecret:kAppSecretDingDingTest];
    
    ///不判断会崩溃*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
    ///设置预定于平台数组
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self platformTypeArray].count>0) {
            [ShareManager  setPreDefinePlatforms:@[@(CAISocialPlatformType_WechatSession),@(CAISocialPlatformType_WechatTimeLine),@(CAISocialPlatformType_DingDing)]];

        }
    });


//    //设置小程序回调app的回调
//    [[UMSocialManager defaultManager] setLauchFromPlatform:(UMSocialPlatformType_WechatSession) completion:^(id userInfoResponse,NSError*error){
//        NSLog(@"setLauchFromPlatform:userInfoResponse:%@",userInfoResponse);
//    }];
//    //移除相应平台的分享，如微信收藏
//    [[UMSocialManager defaultManager]removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];

}


- (NSArray *)platformTypeArray{
    NSArray *arr = ((NSArray*(*)(id,SEL))objc_msgSend)([ShareManager socialManager],sel_registerName("platformTypeArray"));
    return arr;
//    NSArray *arr = [UMSocialManager defaultManager].platformTypeArray;
}

- (BOOL)setPlaform:(CAISocialPlatformType)platformType
            appKey:(NSString *)appKey
         appSecret:(NSString *)appSecret{
    
    BOOL flag = ((BOOL(*)(id,SEL,NSInteger,NSString *, NSString *,NSString *))objc_msgSend)([ShareManager socialManager],sel_registerName("setPlaform:appKey:appSecret:redirectURL:"),platformType,appKey,appSecret,@"http://mobile.umeng.com/social");
    return flag;
//  return [[UMSocialManager defaultManager]setPlaform:type appKey:appKey appSecret:appSecret redirectURL:@"http://mobile.umeng.com/social"];
}

+ (id)umSocialGlobal{
    Class cls = objc_getClass("UMSocialGlobal");
    id (*umSocialGlobal_msgSend)(id,SEL) = (id (*)(id,SEL))objc_msgSend;
    id umSocialGlobal = umSocialGlobal_msgSend(cls,sel_registerName("shareInstance"));
    return umSocialGlobal;
}


+ (id)socialManager{
    Class cls = objc_getClass("UMSocialManager");
    id (*umSocialManager_msgSend)(id,SEL) = (id (*)(id,SEL))objc_msgSend;
    id umSocialManager = umSocialManager_msgSend(cls,sel_registerName("defaultManager"));
    return umSocialManager;
}

- (BOOL)handleOpenURL:(NSURL *)url{

    BOOL flag = ((BOOL(*)(id,SEL,id))objc_msgSend)([ShareManager socialManager],sel_registerName("handleOpenURL:"),url);
    return flag;
}

- (BOOL)handleUniversalLink:(id)userActivity options:(NSDictionary*)options{
    
    BOOL flag = ((BOOL(*)(id,SEL,id,id))objc_msgSend)([ShareManager socialManager],sel_registerName("handleUniversalLink:options:"),userActivity,options);
    return flag;
}


#pragma mark - UI

+ (void)setPreDefinePlatforms:(NSArray *)preDefinePlatforms{
    Class cls = objc_getClass("UMSocialUIManager");
    void (*umSocialUIManager_msgSend)(id,SEL,id) = (void (*)(id,SEL,id))objc_msgSend;
    umSocialUIManager_msgSend(cls,sel_registerName("setPreDefinePlatforms:"),preDefinePlatforms);
//    [UMSocialUIManager setPreDefinePlatforms:preDefinePlatforms];
}

///没有安装的分享平台，怎么显示，目前是该隐藏的就是隐藏，最少是空白弹窗；
+ (void)showShareMenuViewInWindowWithData:(ShareMessageModel *)model{
    
    Class cls = objc_getClass("UMSocialUIManager");
    void (*umSocialUIManager_msgSend)(id,SEL,void(^block)(NSInteger platformType,NSDictionary *userInfo)) = (void (*)(id,SEL,void(^block)(NSInteger platformType,NSDictionary *userInfo)))objc_msgSend;
    umSocialUIManager_msgSend(cls,sel_registerName("showShareMenuViewInWindowWithPlatformSelectionBlock:"),^(NSInteger platformType, NSDictionary *userInfo) {

        NSLog(@"%@,%@",@(platformType),userInfo);
        if ([model isKindOfClass:[ShareMessageWebPageModel class]]) {
            [ShareManager shareWebPageToPlatformType:platformType share:model];
        }
        else if ([model isKindOfClass:[ShareMessageImageModel class]]) {
            [ShareManager shareImageToPlatformType:platformType share:model];
        }
        else if ([model isKindOfClass:[ShareMessageTextModel class]]) {
            [ShareManager shareTextToPlatformType:platformType share:model];
        }
        else if ([model isKindOfClass:[ShareMessageMiniProgramModel class]]) {
            [ShareManager shareMiniProgramToPlatformType:platformType share:model];
        }
    });
    
//    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
//
//        NSLogDebug(@"%@,%@",@(platformType),userInfo);
//        if ([model isKindOfClass:[ShareMessageWebPageModel class]]) {
//            [ShareManager shareWebPageToPlatformType:platformType share:model];
//        }
//        else if ([model isKindOfClass:[ShareMessageImageModel class]]) {
//            [ShareManager shareImageToPlatformType:platformType share:model];
//        }
//        else if ([model isKindOfClass:[ShareMessageTextModel class]]) {
//            [ShareManager shareTextToPlatformType:platformType share:model];
//        }
//        else if ([model isKindOfClass:[ShareMessageMiniProgramModel class]]) {
//            [ShareManager shareMiniProgramToPlatformType:platformType share:model];
//        }
//    }];
}


+ (id)socialMessageObject{
    Class cls = objc_getClass("UMSocialMessageObject");
    id (*umSocialMessageObject_msgSend)(id,SEL) = (id (*)(id,SEL))objc_msgSend;
    id umSocialMessageObject = umSocialMessageObject_msgSend(cls,sel_registerName("messageObject"));
    return umSocialMessageObject;
}


//#pragma mark - 分享图文（新浪支持图文，微信/QQ/dingding不支持）
//
//+ (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType share:(ShareMessageModel *)imageTextModel
//{
//    ShareMessageImageTextModel *model = (ShareMessageImageTextModel *)imageTextModel;
//
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//
//    messageObject.text = model.text;//唯一设置文本的属性；
//
//    if (model.shareImage) {
//        //创建图片内容对象
//        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
//
//        //如果有缩略图，则设置缩略图
//        shareObject.thumbImage = model.thumbImage;
//        shareObject.shareImage = model.shareImage;
//        messageObject.shareObject = shareObject;
//    }
//
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
//
//        if (error) {
//            NSLog(@"************Share fail with error %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];
//}


#pragma mark - 分享图片
+ (void)shareImageToPlatformType:(CAISocialPlatformType)platformType share:(ShareMessageModel *)imageModel
{
    ShareMessageImageModel *model = (ShareMessageImageModel *)imageModel;
    id messageObject = [self socialMessageObject];
    if (model.shareImage) {
        id shareObject = [[NSClassFromString(@"UMShareImageObject") alloc]init];
        [shareObject setValue:model.thumbImage forKey:@"thumbImage"];
        [shareObject setValue:model.shareImage forKey:@"shareImage"];
        [messageObject setValue:shareObject forKey:@"shareObject"];
    }
    
    ((void(*)(id,SEL,NSInteger,id,id,void (^UMSocialRequestCompletionHandler)(id result,NSError *error)))objc_msgSend)([ShareManager socialManager],sel_registerName("shareToPlatform:messageObject:currentViewController:completion:"),platformType,messageObject,nil,^(id data, NSError *error) {
        
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    });

    
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//
//    if (model.shareImage) {
//        //创建图片内容对象
//        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
//        shareObject.thumbImage = model.thumbImage;
//        shareObject.shareImage = model.shareImage;
//        messageObject.shareObject = shareObject;
//    }

//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
//
//        if (error) {
//            NSLog(@"************Share fail with error %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];
}


#pragma mark - 分享文本;只有text有效，其它属性无效；
+ (void)shareTextToPlatformType:(CAISocialPlatformType)platformType share:(ShareMessageModel *)model
{
    //分享数据不能为空nil
    ShareMessageTextModel *textModel = (ShareMessageTextModel *)model;
    
    
    id messageObject = [self socialMessageObject];
    [messageObject setValue:textModel.text forKey:@"text"];
    ((void(*)(id,SEL,NSInteger,id,id,void (^UMSocialRequestCompletionHandler)(id result,NSError *error)))objc_msgSend)([ShareManager socialManager],sel_registerName("shareToPlatform:messageObject:currentViewController:completion:"),platformType,messageObject,nil,^(id data, NSError *error) {
        
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    });
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    messageObject.text = textModel.text;
//
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
//
//        if (error) {
//            NSLog(@"************Share fail with error %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];

}


#pragma mark - web分享：

///web分享：
///微信聊天：标题+缩率图+描述+url;
///微信朋友圈：只有标题+缩率图+url，没有描述；
///dingding:标题+缩率图+描述+url；
+ (void)shareWebPageToPlatformType:(CAISocialPlatformType)platformType share:(ShareMessageModel *)webModel
{
    ShareMessageWebPageModel *model = (ShareMessageWebPageModel *)webModel;
    //创建分享消息对象
    id messageObject = [self socialMessageObject];
    //创建网页内容对象
    id shareObject = ((id(*)(id,SEL,NSString *,id, id))objc_msgSend)([ShareManager socialManager],sel_registerName("shareObjectWithTitle:descr:thumImage:"),model.title,model.content,model.thumbImage);
    //设置网页地址
    [shareObject setValue:model.webpageUrl forKey:@"webpageUrl"];
    //分享消息对象设置分享内容对象
    [messageObject setValue:shareObject forKey:@"shareObject"];
    //调用分享接口
    ((void(*)(id,SEL,NSInteger,id,id,void (^UMSocialRequestCompletionHandler)(id result,NSError *error)))objc_msgSend)([ShareManager socialManager],sel_registerName("shareToPlatform:messageObject:currentViewController:completion:"),platformType,messageObject,nil,^(id data, NSError *error) {
        
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    });
    
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.title  descr:model.content thumImage:model.thumbImage];
//    shareObject.webpageUrl = model.webpageUrl;
//    messageObject.shareObject = shareObject;
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
//        if (error) {
//            NSLog(@"Share fail with error: %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];
}


+ (void)shareMiniProgramToPlatformType:(CAISocialPlatformType)platformType share:(ShareMessageModel *)miniProgramModel
{
    if (![miniProgramModel isKindOfClass:[ShareMessageMiniProgramModel class]]) {
        
        return;
    }
    ShareMessageMiniProgramModel *model = (ShareMessageMiniProgramModel *)miniProgramModel;
    
    
    id messageObject = [self socialMessageObject];
    id shareObject = ((id(*)(id,SEL,NSString *,id, id))objc_msgSend)([ShareManager socialManager],sel_registerName("shareObjectWithTitle:descr:thumImage:"),model.title,model.content,model.thumbImage);
    [shareObject setValue:model.webpageUrl forKey:@"webpageUrl"];
    [shareObject setValue:model.userName forKey:@"userName"];
    [shareObject setValue:model.path forKey:@"path"];
    [shareObject setValue:model.hdImageData forKey:@"hdImageData"];
    [shareObject setValue:@(model.miniProgramType) forKey:@"miniProgramType"];

    [messageObject setValue:shareObject forKey:@"shareObject"];
    
    ((void(*)(id,SEL,NSInteger,id,id,void (^UMSocialRequestCompletionHandler)(id result,NSError *error)))objc_msgSend)([ShareManager socialManager],sel_registerName("shareToPlatform:messageObject:currentViewController:completion:"),platformType,messageObject,nil,^(id data, NSError *error) {
        
        if (error) {
            NSLog(@"Share fail with error: %@*********",error);
        }else{
            if ([data isKindOfClass:NSClassFromString(@"UMSocialShareResponse")]) {
//                UMSocialShareResponse *resp = data;
//                //分享结果消息
//                UMSocialLogInfo(@"response message is %@",resp.message);
//                //第三方原始返回的数据
//                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
//                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    });
    
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    //wx小程序
//    UMShareMiniProgramObject *shareObject = [UMShareMiniProgramObject shareObjectWithTitle:model.title  descr:model.content thumImage:model.thumbImage];
//    //兼容微信低版本网页地址
//    shareObject.webpageUrl = model.webpageUrl;
//    shareObject.userName = model.userName;
//    shareObject.path = model.path;
//    shareObject.hdImageData = model.hdImageData;
//    shareObject.miniProgramType = model.miniProgramType;
//    //分享消息对象设置分享内容对象
//    messageObject.shareObject = shareObject;
//
//    //调用分享接口
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
//        if (error) {
//            NSLog(@"Share fail with error: %@*********",error);
//        }else{
//            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
//                UMSocialShareResponse *resp = data;
//                //分享结果消息
//                UMSocialLogInfo(@"response message is %@",resp.message);
//                //第三方原始返回的数据
//                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
//            }else{
//                UMSocialLogInfo(@"response data is %@",data);
//            }
//        }
//    }];
}

@end
 


